package com.jiang.daily.Q3298;

import java.util.Arrays;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/01/10 0:37
 */
class Solution {
    public long validSubstringCount(String word1, String word2) {
        int[] word = new int[26];
        for (char c: word2.toCharArray()) {
            word[c - 'a']--;
        }
        char[] arr = word1.toCharArray();
        int len = arr.length;
        int cnt = (int) Arrays.stream(word).filter(c -> c < 0).count();
        int l = 0;
        int r = 0;
        long res = 0;
        while (l < len) {
            while (r < len && cnt != 0) {
                if (++word[arr[r] - 'a'] == 0) {
                    cnt--;
                }
                r++;
            }
            if (cnt == 0) {
                res += len - r + 1;
            }
            if (--word[arr[l] - 'a'] == -1) {
                cnt++;
            }
            l++;
        }
        return res;
    }
}
